package interfaz;

import clases.ClsContraladorEventos;
import clases.ClsDatabase;
import clases.ClsMetodos;
import clases.ClsSesion;
import clases.ClsValidacion;
import java.awt.Image;
import javax.swing.DefaultComboBoxModel;
import javax.swing.ImageIcon;
import javax.swing.JDialog;
import javax.swing.JOptionPane;
import javax.swing.JTable;

/**
 *
 * @author mk
 */
public class dlg_NewProyecto extends javax.swing.JDialog {

    private ClsDatabase bd = new ClsDatabase();
    private ClsMetodos metodos = new ClsMetodos();
    private ClsContraladorEventos contraladorEventos = new ClsContraladorEventos();
//    private ClsSesion sesion=new ClsSesion();
    private DefaultComboBoxModel modelCboPlantilla = new DefaultComboBoxModel();
    private JTable table;
    private dlgProyectos dialog;
    private String id = "-1";
    private boolean editarUpdate = false;

    /**
     * Creates new form dlg_NewProyecto
     *
     * @param parent
     * @param modal
     */
    public dlg_NewProyecto(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        this.setLocationRelativeTo(null);//Centramos la ventana
    }

    public dlg_NewProyecto(java.awt.Frame parent, boolean modal, JDialog dialog, JTable table) {
        super(parent, modal);
        initComponents();
        this.setLocationRelativeTo(null);//Centramos la ventana
        this.dialog = (dlgProyectos) dialog;
        this.table = table;

        metodos._iconJDialog(this);

        modelCboPlantilla.addElement("0");//Plantilla
        modelCboPlantilla.addElement("1");//Normal
    }
//___________________________________________________________________________________ Soy una barra separadora :)

    public void Editar(int opcion) {
        int fila = table.getSelectedRow();//Obtenemos la fila seleccionada
        if (fila != -1) {//Si no se a seleccionado alguna row de la Tabla hacer...
            Object[][] datos = bd.select("proyecto",
                    "idproyecto,nombre,cliente,lugar,idusuario,plantilla,proyectista,fecha_registro",
                    "idproyecto='" + table.getValueAt(fila, 0) + "' ");
            if (datos != null) {
                if (opcion == 1) {
                    id = datos[0][0].toString();
                    editarUpdate = true;
                } else {
                    id = "";
                    editarUpdate = false;
                }

                txaDescripcion.setText(datos[0][1].toString());
                txtCliente.setText(datos[0][2].toString());
                txtLugar.setText(datos[0][3].toString());
                txtProyectista.setText(datos[0][6].toString());
                metodos.fecha_date_choseser_devuelve(datos[0][7].toString(), dateChooserCombo1);
//                if (datos[0][5].equals("0")) {
//                    cboPlantilla.setSelectedIndex(0);
//                }else{
//                    cboPlantilla.setSelectedIndex(1);
//                }
                txaDescripcion.setSelectionStart(0);
                txaDescripcion.setSelectionEnd(txaDescripcion.getText().length());
                
                setVisible(true);
            } else {
                System.err.println("------------------------>ERROR NO PREVISTO<--------------------------------");
            }
        } else {
            javax.swing.JOptionPane.showMessageDialog(this, "Seleccione un Proyecto");
            dispose();
        }
    }

    public void Guardar() {
        String nombreString = txaDescripcion.getText().toString();
        boolean seRepite = true;
        if (editarUpdate) {//Si se presiona EDITAR, entonces el nombre se actualiza, no es un INSERT
            seRepite = false;
        } else {//Verificamos si se repite
            seRepite = bd.verif_repite("SELECT nombre FROM proyecto WHERE nombre='" + nombreString + "'");
        }
        if (!seRepite) {//Verificamos si se Repite el Nombre de Unidad
            if (ClsValidacion.tieneCamposVacios(fondo)) {
                JOptionPane.showMessageDialog(null, "Se tiene que llenar todos los campos");
                return;
            }
            String clienteString = txtCliente.getText().toString();
            String proyectistaString = txtProyectista.getText().toString();
            String lugarString = txtLugar.getText().toString();
            String idusuario = ClsSesion.iduser.toString();

            String plantillaString = "1";
//            plantillaString=modelCboPlantilla.getElementAt(cboPlantilla.getSelectedIndex()).toString();

            if (editarUpdate) {
                //UPDATE
                //Realizamos la consulta
                boolean seInserto = bd.update("proyecto",
                        "nombre='" + nombreString + "',cliente='" + clienteString + "',proyectista='" + proyectistaString + "',lugar='" + lugarString
                        + "',idusuario='" + idusuario + "', fecha_registro='" + metodos.fecha_date_choseser(dateChooserCombo1.getText()) + "' ",
                        "idproyecto=" + id);
                if (!seInserto) {
                    JOptionPane.showMessageDialog(null, "No se puedo Actualizar el Proyecto");
                }
                editarUpdate = false;
            } else {
                //INSERT
                //Realizamos la consulta
                // me.fecha_date_choseser(dateChooserCombo1.getText())
                boolean seInserto = bd.insert("proyecto",
                        "nombre,cliente,lugar,idusuario,plantilla,proyectista,fecha_registro, total_proyecto, porcentaje_gg, monto_gg, porcentaje_uti, monto_uti, igv, utilidad_ver, igv_ver",
                        "'" + nombreString + "','" + clienteString + "','" + lugarString + "','" + idusuario + "','" + plantillaString + "' ,'" + proyectistaString + "','" + metodos.fecha_date_choseser(dateChooserCombo1.getText()) + "','0','0','0','0','0','18','1','1'");
                if (!seInserto) {
                    JOptionPane.showMessageDialog(null, "No se puedo crear el nuevo Proyecto");
                }
            }
            dialog._iniciar();
            this.dispose();
        } else {
            JOptionPane.showMessageDialog(null, "El nombre del proyecto ya existe");
            txaDescripcion.requestFocus();
            txaDescripcion.setSelectionStart(0);
            txaDescripcion.setSelectionEnd(txaDescripcion.getText().length());
        }
    }

    public void Cancelar() {
        this.dispose();
    }

    private void Limpiar() {
        txaDescripcion.setText("");
        txtLugar.setText("");
        txtCliente.setText("");
//        cboPlantilla.setSelectedIndex(-1);
        txaDescripcion.requestFocus();
    }
//___________________________________________________________________________________ Soy una barra separadora :)

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        fondo = new javax.swing.JPanel();
        btnGuardar = new javax.swing.JButton();
        btnCancelar = new javax.swing.JButton();
        jPanel2 = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        txtCliente = new javax.swing.JTextField();
        txtLugar = new javax.swing.JTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        txaDescripcion = new javax.swing.JTextArea();
        txtProyectista = new javax.swing.JTextField();
        dateChooserCombo1 = new datechooser.beans.DateChooserCombo();
        jLabel5 = new javax.swing.JLabel();
        jLabel10 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Datos del Proyecto");

        fondo.setBackground(new java.awt.Color(225, 235, 247));
        fondo.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        btnGuardar.setText("Guardar");
        btnGuardar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnGuardarActionPerformed(evt);
            }
        });
        fondo.add(btnGuardar, new org.netbeans.lib.awtextra.AbsoluteConstraints(90, 240, 100, -1));

        btnCancelar.setText("Cancelar");
        btnCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelarActionPerformed(evt);
            }
        });
        fondo.add(btnCancelar, new org.netbeans.lib.awtextra.AbsoluteConstraints(340, 240, 100, 31));

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder(""));
        jPanel2.setOpaque(false);
        jPanel2.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        jLabel2.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        jLabel2.setText("Nombre Py:");
        jPanel2.add(jLabel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 20, 76, 20));

        jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        jLabel1.setText("Cliente:");
        jPanel2.add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(40, 80, -1, 20));

        jLabel3.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        jLabel3.setText("Ubicación:");
        jPanel2.add(jLabel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 140, 58, 20));

        jLabel4.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        jLabel4.setText("Proyectista:");
        jPanel2.add(jLabel4, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 110, -1, 20));

        txtCliente.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                txtClienteKeyTyped(evt);
            }
        });
        jPanel2.add(txtCliente, new org.netbeans.lib.awtextra.AbsoluteConstraints(90, 80, 396, -1));

        txtLugar.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                txtLugarKeyTyped(evt);
            }
        });
        jPanel2.add(txtLugar, new org.netbeans.lib.awtextra.AbsoluteConstraints(90, 140, 396, -1));

        txaDescripcion.setColumns(20);
        txaDescripcion.setFont(new java.awt.Font("Tahoma", 0, 11)); // NOI18N
        txaDescripcion.setLineWrap(true);
        txaDescripcion.setRows(3);
        txaDescripcion.setWrapStyleWord(true);
        txaDescripcion.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                txaDescripcionKeyTyped(evt);
            }
        });
        jScrollPane1.setViewportView(txaDescripcion);

        jPanel2.add(jScrollPane1, new org.netbeans.lib.awtextra.AbsoluteConstraints(90, 20, 396, -1));
        jPanel2.add(txtProyectista, new org.netbeans.lib.awtextra.AbsoluteConstraints(90, 110, 396, -1));

        dateChooserCombo1.setCurrentView(new datechooser.view.appearance.AppearancesList("Swing",
            new datechooser.view.appearance.ViewAppearance("custom",
                new datechooser.view.appearance.swing.SwingCellAppearance(new java.awt.Font("Tahoma", java.awt.Font.PLAIN, 11),
                    new java.awt.Color(0, 0, 0),
                    new java.awt.Color(0, 0, 255),
                    false,
                    true,
                    new datechooser.view.appearance.swing.ButtonPainter()),
                new datechooser.view.appearance.swing.SwingCellAppearance(new java.awt.Font("Tahoma", java.awt.Font.PLAIN, 11),
                    new java.awt.Color(0, 0, 0),
                    new java.awt.Color(0, 0, 255),
                    true,
                    true,
                    new datechooser.view.appearance.swing.ButtonPainter()),
                new datechooser.view.appearance.swing.SwingCellAppearance(new java.awt.Font("Tahoma", java.awt.Font.PLAIN, 11),
                    new java.awt.Color(0, 0, 255),
                    new java.awt.Color(0, 0, 255),
                    false,
                    true,
                    new datechooser.view.appearance.swing.ButtonPainter()),
                new datechooser.view.appearance.swing.SwingCellAppearance(new java.awt.Font("Tahoma", java.awt.Font.PLAIN, 11),
                    new java.awt.Color(128, 128, 128),
                    new java.awt.Color(0, 0, 255),
                    false,
                    true,
                    new datechooser.view.appearance.swing.LabelPainter()),
                new datechooser.view.appearance.swing.SwingCellAppearance(new java.awt.Font("Tahoma", java.awt.Font.PLAIN, 11),
                    new java.awt.Color(0, 0, 0),
                    new java.awt.Color(0, 0, 255),
                    false,
                    true,
                    new datechooser.view.appearance.swing.LabelPainter()),
                new datechooser.view.appearance.swing.SwingCellAppearance(new java.awt.Font("Tahoma", java.awt.Font.PLAIN, 11),
                    new java.awt.Color(0, 0, 0),
                    new java.awt.Color(255, 0, 0),
                    false,
                    false,
                    new datechooser.view.appearance.swing.ButtonPainter()),
                (datechooser.view.BackRenderer)null,
                false,
                true)));
    dateChooserCombo1.setCalendarBackground(new java.awt.Color(225, 235, 247));
    dateChooserCombo1.setCalendarPreferredSize(new java.awt.Dimension(325, 180));
    dateChooserCombo1.setBehavior(datechooser.model.multiple.MultyModelBehavior.SELECT_SINGLE);
    dateChooserCombo1.addCommitListener(new datechooser.events.CommitListener() {
        public void onCommit(datechooser.events.CommitEvent evt) {
            dateChooserCombo1OnCommit(evt);
        }
    });
    jPanel2.add(dateChooserCombo1, new org.netbeans.lib.awtextra.AbsoluteConstraints(90, 170, -1, -1));

    jLabel5.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
    jLabel5.setText("Fecha:");
    jPanel2.add(jLabel5, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 170, 58, 20));

    fondo.add(jPanel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 11, 510, 210));

    jLabel10.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resource/icon/principales/fondo_dialog.jpg"))); // NOI18N
    fondo.add(jLabel10, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 450, 280));

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addComponent(fondo, javax.swing.GroupLayout.DEFAULT_SIZE, 553, Short.MAX_VALUE)
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addComponent(fondo, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
    );

    pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnGuardarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnGuardarActionPerformed
        Guardar();
    }//GEN-LAST:event_btnGuardarActionPerformed

    private void btnCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelarActionPerformed
        Cancelar();
    }//GEN-LAST:event_btnCancelarActionPerformed

    private void txtClienteKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtClienteKeyTyped
        contraladorEventos.cantidadMaximaCaracteresJTextField(evt, txtLugar, 200);
    }//GEN-LAST:event_txtClienteKeyTyped

    private void txtLugarKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtLugarKeyTyped
        contraladorEventos.cantidadMaximaCaracteresJTextField(evt, txtLugar, 200);
    }//GEN-LAST:event_txtLugarKeyTyped

    private void txaDescripcionKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txaDescripcionKeyTyped
        contraladorEventos.cantidadMaximaCaracteresJTextArea(evt, txaDescripcion, 200);
    }//GEN-LAST:event_txaDescripcionKeyTyped

    private void dateChooserCombo1OnCommit(datechooser.events.CommitEvent evt) {//GEN-FIRST:event_dateChooserCombo1OnCommit
        if (dateChooserCombo1.getText().length() == 0) {
            JOptionPane.showMessageDialog(null, "Seleccione la fecha");
        } else {
//            pregunta_4_9();
//            pregunta_4_11();
        }
    }//GEN-LAST:event_dateChooserCombo1OnCommit

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(dlg_NewProyecto.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(dlg_NewProyecto.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(dlg_NewProyecto.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(dlg_NewProyecto.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the dialog */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                dlg_NewProyecto dialog = new dlg_NewProyecto(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnCancelar;
    private javax.swing.JButton btnGuardar;
    private datechooser.beans.DateChooserCombo dateChooserCombo1;
    private javax.swing.JPanel fondo;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextArea txaDescripcion;
    private javax.swing.JTextField txtCliente;
    private javax.swing.JTextField txtLugar;
    private javax.swing.JTextField txtProyectista;
    // End of variables declaration//GEN-END:variables
}
